/* jslight.js -- A slight javascript highlighter */
/* Copyright 2007 Rici Lake */
/* You may use this software under the terms of the MIT license
 * as shown at http://www.opensource.org/licenses/mit-license.php
 */

if (!window.jslight) {jslight = {"language": {}}}

(function() {

  var xl = { "&": "&amp;", "<": "&lt;", ">": "&gt;" };
  function entify(s) { return s.replace(/[&<>]/g, function(c) { return xl[c]; }) };
  jslight.entify = entify;
  
  function getEntifiedText(n) {
    var s="";
    var children=n.childNodes;
    for (var i = 0; i < children.length; i++) {
      var child = children[i];
      if (child.nodeType == 3) s += entify(child.data);
      else if (child.tagName == "BR" || child.tagName == "br") s += "\n";
      else s += getEntifiedText(child);
    }
    return s;
  }
  jslight.getEntifiedText = getEntifiedText;

  function getTrimmedEntifiedText(n) {
    return getEntifiedText(n).replace(/^\s+/, "").replace(/[ \t\r]+\n/g, "\n");
  }
  jslight.getTrimmedEntifiedText = getTrimmedEntifiedText;

  jslight.annotate = function(word, type) {
    return (type && type != "none") ? "<span class='code_"+type+"'>"+word+"</span>" : word;
  }

  // 
  jslight.addAnnotations = function(hash, listoflists) {
    for (var i = 0; i < listoflists.length; i++) {
      var typelist = listoflists[i];
      var type = typelist[0];
      var words = typelist[1];
      for (var j = 0; j < words.length; j++) hash[words[j]] = type;
    }
    return hash;
  }

  function decodify(s) {
    var segs = s.split(/\n\n/);
    var incode = false;
    for (var i = 0; i < segs.length; i++) {
      var elt = segs[i];
      if (!incode) {
        var r = elt.match(/^\[code(?:\s+(\w*))?\]/i);
        if (r) {
          elt = "<div class='code'><code" +
                (r[1] ? " class='"+r[1].toLowerCase()+"'>" : ">") +
                elt.slice(r[0].length);
          incode = true;
        }
      }
      if (!incode) elt = "<p>"+elt+"</p>";
      else if (elt.slice(-7).toLowerCase() === "[/code]") {
        elt = elt.slice(0, -7)+"</code></div>";
        incode = false;
      }
      segs[i] = elt;
    }
    return segs.join("\n\n");
  }

  jslight.mangleBloggerComments = function() {
    var c = document.getElementsByTagName("dd");
    for (var i = 0; i < c.length; i++) {
      var cmt = c[i];
      if (cmt.getAttribute("class") === "comment-body") {
        cmt.innerHTML = decodify(getEntifiedText(cmt.getElementsByTagName("p")[0]));
      }
    }
  }

  function highlight(node, language) {
    var code = getTrimmedEntifiedText(node);
    if (language && language in jslight.language)
      code = jslight.language[language].getHighlighter()(code);
    node.innerHTML = code;
  }
  jslight.highlight = highlight;
  
  jslight.highlightDocument = function () {
    var codes = document.getElementsByTagName("code");
    for (var i = 0; i < codes.length; i++) {
      highlight(codes[i], codes[i].getAttribute("class"));
    }
  }
})();
